package com.kongshidian.ui;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kongshidian.App;
import com.kongshidian.R;
import com.kongshidian.bean.Condition;
import com.kongshidian.bean.PageEntityForSearch;
import com.kongshidian.bean.ProductCategory.AppLayout;
import com.kongshidian.bean.Search;
import com.kongshidian.http.WebClient;
import com.kongshidian.http.WebException;
import com.kongshidian.ui.view.AbsViewHolderAdapter;
import com.kongshidian.ui.view.RefreshViewLoadMoreProxy;
import com.kongshidian.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @author fbl
 * 搜索出来的商品展示
 */
public class SearchListActivity extends BaseActivity implements OnLoadDataActionListener{
	@ViewInject(id = R.id.search_list_radio0 ,click = "butClick") RadioButton mRadio0;
	@ViewInject(id = R.id.search_list_radio1 ,click = "butClick") RadioButton mRadio1;
	@ViewInject(id = R.id.search_list_radio2 ,click = "butClick") RadioButton mRadio2;
	@ViewInject(id = R.id.search_list_radio3 ,click = "butClick") RadioButton mRadio3;
	@ViewInject(id = R.id.search_list_progressBar ) ProgressBar mprogress;
	@ViewInject(id = R.id.search_list_lin ) LinearLayout mLin;
	@ViewInject(id = R.id.search_list_empty_relat ) RelativeLayout mEmptyRelat;
	@ViewInject(id = R.id.serch_list_title ) TextView mTitleText;
	@ViewInject(id = R.id.search_herd_back_icon , click = "butClick" ) ImageButton backImageButton; 
	@ViewInject(id = R.id.search_list_right_second_image , click = "butClick" ) ImageView mlistAdapterImg; 
	@ViewInject(id = R.id.search_list_right_image , click = "butClick" ) ImageView mSearchImg; 
	@ViewInject(id = R.id.back_top_img ,click = "butClick") ImageView mBackTopImg;

	PullToRefreshGridView mRefreshListView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	private String mSearchKeyWord = ""; //搜索的内容
	private String mSearchcategory = ""; //搜索的分类
	private String from = ""; //从哪一个activity跳进来
	private String shop_id; //搜索那一家店
	private SearchListAdapter mAdapter;
	private List<Search> mSearch;
	private int nowPage = 1;
	private String sortWay="-solr_hits";
	private List<Condition> mConditions;
	private String conditions = "";
	private boolean isFirst = true;
	private SearchConditionAdapter mConAdapter;
	private AppLayout appLayout  = AppLayout.LIST;
	private Handler mHandler  = new MyHandler(this);

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		from = getIntent().getStringExtra("from");
		mSearchKeyWord = getIntent().getStringExtra("searchStr");
		mSearchcategory = getIntent().getStringExtra("CATEGORY_NAME");
		shop_id = getIntent().getStringExtra("ShopId");
		
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_search_list);
		FinalActivity.initInjectedView(this);
		if(mSearchKeyWord != null && !"".equals(mSearchKeyWord)){
			mTitleText.setText(mSearchKeyWord);
		}else {
			mTitleText.setText(mSearchcategory);
		}
		
		appLayout = AppLayout.GRID.name().equals(getIntent().getStringExtra("APP_LAYOUT")) ? AppLayout.GRID : AppLayout.LIST;
		if(appLayout == AppLayout.LIST){
			mlistAdapterImg.setBackgroundResource(R.drawable.productlist_top_grid);
		}else {
			mlistAdapterImg.setBackgroundResource(R.drawable.productlist_top_list);
		}
		
		mRefreshListView = (PullToRefreshGridView) findViewById(R.id.search_list);
		mRefreshListView.setEmptyView(mEmptyRelat);
		mRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
		
		if (appLayout == AppLayout.GRID) mRefreshListView.getRefreshableView().setNumColumns(GridView.AUTO_FIT); // 2
		
		mAdapter = new SearchListAdapter(this,appLayout == AppLayout.LIST ? R.layout.item_search_list:R.layout.item_search_grid);
		mRefreshListView.setAdapter(mAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshListView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);

		mRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {

				Intent intent = new Intent(SearchListActivity.this,ProductDetailActivity.class);
				intent.putExtra("productID", mAdapter.getData().get(position).getId()+"");
				startActivity(intent);
			}

		});

		mLoadMoreProxy.refreshing();

		mRefreshListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
			}

			@Override
			public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
				if(arg1 != 0){  
					mBackTopImg.setVisibility(View.VISIBLE);
				}else {
					mBackTopImg.setVisibility(View.GONE);
				}
			}
		});
		
	}

	@Override
	public void onRefresh(int page) {
		updateSearchList(1, true);
	}
	@Override
	public void onLoadMore(int page) {
		nowPage ++;
		updateSearchList(nowPage, false);
	}

	//请求数据
	private void updateSearchList(final int pageNum,final boolean isRefresh){
		//		mLoadMoreProxy.loadDataActionComplete(false);

		new Thread(){
			public void run() {
				try{
					WebClient client = WebClient.getInstance(SearchListActivity.this);

					PageEntityForSearch<Search> entry = client.fuzzy(shop_id,conditions,mSearchKeyWord, mSearchcategory, pageNum, 20, sortWay);

					mSearch = entry.getContent();

				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
						mSearch = null;
					else
						e.printStackTrace();
				}catch (Exception e) {
					App.showShortToast(R.string.unknownerror);
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

		//		mLoadMoreProxy.loadDataActionComplete(true);
	}


	public class SearchListAdapter extends AbsViewHolderAdapter<Search>{

		public SearchListAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, Search itemData) {
			ImageView mImage = getViewFromHolder(R.id.item_search_image);
			TextView mNameText = getViewFromHolder(R.id.item_search_name_txt);
			TextView mPriceText = getViewFromHolder(R.id.item_search_price_txt);

			ImageLoader.getInstance().displayImage(itemData.getImage(), mImage);
			mNameText.setText(itemData.getName());
			mPriceText.setText("￥"+itemData.getPrice());
		}

	}

	@SuppressLint("HandlerLeak") 
	private class MyHandler extends Handler{
		
		private WeakReference<Activity> mActivity;
		
		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					if(mSearch == null){
						App.showShortToast("没有搜索到结果");
					}
					mAdapter.update(mSearch);
					mRefreshListView.onRefreshComplete();
					canClick(true);
					break;
				case 1:
					if(mSearch == null){
						App.showShortToast("到底了");
					}
					mAdapter.append(mSearch);
					mRefreshListView.onRefreshComplete();
					canClick(true);
					break;
				case 2:
					dismissLoadingDialog();
					for (int i = 0; i < mConditions.size(); i++) {
						mConditions.get(i).getOptions().add(0, "全部");
					}
					mConAdapter.update(mConditions);
					break;

				default:
					break;
				}
			}
		}
	}


	public void butClick(View v){
		//返回
		if( v == backImageButton ){
			finish();
		}
		//改变视图
		if( v == mlistAdapterImg){
			if(appLayout == AppLayout.LIST ){
				appLayout = AppLayout.GRID;
				mlistAdapterImg.setBackgroundResource(R.drawable.productlist_top_list);
			}else if(appLayout == AppLayout.GRID ){
				appLayout = AppLayout.LIST;
				mlistAdapterImg.setBackgroundResource(R.drawable.productlist_top_grid);
			}
			if (appLayout == AppLayout.GRID) 
				mRefreshListView.getRefreshableView().setNumColumns(GridView.AUTO_FIT);
			else 
				mRefreshListView.getRefreshableView().setNumColumns(1);
			
			mAdapter = new SearchListAdapter(this,appLayout == AppLayout.LIST ? R.layout.item_search_list:R.layout.item_search_grid);
			mRefreshListView.setAdapter(mAdapter);
			onRefresh(1);

		}
		//筛选
		if( v == mSearchImg){
			new PopupWindows(SearchListActivity.this,mSearchImg);
		}

		//相关
		if(v == mRadio0){
			mRadio2.setCompoundDrawables(null,null,null,null);
			sortWay = "-solr_hits"; //按点击量排序
			onRefresh(1);
			mRefreshListView.requestFocus();
			mRefreshListView.setSelection(0);
			canClick(false);	
		}
		//销量
		if(v == mRadio1){
			mRadio2.setCompoundDrawables(null,null,null,null);
			sortWay = "solr_sales";
			onRefresh(1);
			mRefreshListView.requestFocus();
			mRefreshListView.setSelection(0);
			canClick(false);
		}
		//价格
		if(v == mRadio2){
			if("solr_price".equals(sortWay) ){
				Drawable drawable= getResources().getDrawable(R.drawable.ico_arrow_down_checked);
				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
				mRadio2.setCompoundDrawables(null,null,drawable,null);
				App.showLog("1111");
				sortWay = "-solr_price";
			}else {
				Drawable drawable= getResources().getDrawable(R.drawable.ico_arrow_up_checked);
				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
				mRadio2.setCompoundDrawables(null,null,drawable,null);
				App.showLog("2222");
				sortWay = "solr_price";
			}
			onRefresh(1);
			mRefreshListView.requestFocus();
			mRefreshListView.setSelection(0); //此操作是为了让列表返回到
			canClick(false);
		}
		//新品
		if(v == mRadio3){
			mRadio2.setCompoundDrawables(null,null,null,null);
			sortWay = "-solr_updateDate";
			onRefresh(1);
			mRefreshListView.requestFocus();
			mRefreshListView.setSelection(0);
			canClick(false);
		}
		//返回顶部
		if (v == mBackTopImg) {
			mRefreshListView.requestFocus();
			mRefreshListView.setSelection(0); //此操作是为了让列表返回到顶部
		}
		
	}

	public void canClick(boolean b){
		mRadio0.setClickable(b);
		mRadio1.setClickable(b);
		mRadio2.setClickable(b);
		mRadio3.setClickable(b);
		if(b){
			mprogress.setVisibility(View.GONE);
		}else {
			mprogress.setVisibility(View.VISIBLE);
		}

	}

	private void getConditionList() {
		showLoadingDialog("");
		new Thread(){
			public void run() {
				try {
					mConditions = WebClient.getInstance(SearchListActivity.this).condition(shop_id,mSearchKeyWord, mSearchcategory);
					mHandler.sendEmptyMessage(2);
				} catch (WebException e) {
					dismissLoadingDialog();
					e.printStackTrace();
				}
			};
		}.start();
	}

	public class PopupWindows extends PopupWindow {

		@SuppressWarnings({ "deprecation" })
		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_search_condition_pop, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.item_pop_con_lin);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();
			
			view.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
					dismiss();
					return false;
				}
			});

			ImageView mCloseImg = (ImageView) view.findViewById(R.id.item_pop_con_close_img);
			TextView resultText = (TextView) view.findViewById(R.id.result_serch_condition);
			Button mSureBut = (Button) view.findViewById(R.id.item_pop_con_sure_but);
			ListView mConditionList = (ListView) view.findViewById(R.id.item_pop_con_list);
			mConAdapter = new SearchConditionAdapter(SearchListActivity.this, R.layout.item_search_condition);
			mConditionList.setAdapter(mConAdapter);
			if( isFirst ){
				getConditionList();
				isFirst = false;
			}else {
				mConAdapter.update(mConditions);
			}

			//			if(mConditions == null || mConditions.size()< 4){
			//				lp.height = 420;
			//			}else {
			//				lp.height = 650;
			//			}
			
			resultText.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View paramView) {
					for (int i = 0; i < mConditions.size(); i++) {
						mConditions.get(i).setOptionid(0);
					}
					mConAdapter.update(mConditions);
					
				}
			});

			mConditionList.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent,
						View view, final int position, long id) {

					Condition mCondition = mConAdapter.getData().get(position);
					String name = mCondition.getName() == null ? getNameString(mCondition.getId()+""):mCondition.getName();
					String [] aa = new String[mCondition.getOptions().size()];
					for (int i = 0; i < aa.length; i++) {
						aa[i] = mCondition.getOptions().get(i);
					}
					new AlertDialog.Builder(SearchListActivity.this).setTitle(name).setSingleChoiceItems(
							aa, mCondition.getOptionid(),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									mConditions.get(position).setOptionid(which);
									dialog.dismiss();
									mConAdapter.update(mConditions);
								}
							}).setNegativeButton("取消", null).show();


				}

			});

			mCloseImg.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View paramView) {
					dismiss();	
				}
			});
			mSureBut.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					conditions = "";
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					//	
					for (int i = 0; i < mConditions.size(); i++) {
						String ss = mConditions.get(i).getOptions().get(mConditions.get(i).getOptionid());
						if("全部".equals(ss)){
							ss = "";
						}
						params.add(new BasicNameValuePair(mConditions.get(i).getId(), ss));
					}
					HttpEntity reqEntity = null;
					try {
						reqEntity = new UrlEncodedFormEntity(params, "utf-8");
						conditions = EntityUtils.toString(reqEntity);
					} catch (ParseException | IOException e) {
						e.printStackTrace();
					}
					dismiss();
					onRefresh(1);
					canClick(false);

				}
			});

		}
	}

	private class SearchConditionAdapter extends AbsViewHolderAdapter<Condition>{

		public SearchConditionAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, Condition itemData) {

			TextView text1 = getViewFromHolder(R.id.search_condition_text1);
			TextView text2 = getViewFromHolder(R.id.search_condition_text2);

			int choiseid = itemData.getOptionid();
			text1.setText(itemData.getName() == null ? getNameString(itemData.getId()+""):itemData.getName());

			text2.setText(itemData.getOptions().get(choiseid).toString());

		}

	}

	private String getNameString(String str){
		if("solr_price".equals(str)){
			return "价格";
		}else if ("solr_brand".equals(str)) {
			return "品牌";
		}else if ("solr_productCategory".equals(str)) {
			return "分类";
		}else {
			return str;
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}

}
